<template>
  <Dialog v-model="dialogVisible" :title="dialogState.dialogTitle" :width="dialogState.dialogWidth">
    <el-form
      ref="Step1Ref"
      :model="formStep1Data"
      :rules="formStep1Rules"
      label-width="80px"
      @submit="submitForm"
    >
      <el-form-item label="任务名称" prop="name">
        <ns-input v-model="formStep1Data.name" placeholder="请输入任务名称" />
      </el-form-item>
    </el-form>

    <div class="c-file mb-15px">
      <span>选择文件</span>
    </div>

    <div>
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="mb-5px"
        label-width="85px"
      >
        <el-form-item label="文件组名称" prop="groupName">
          <ns-input
            v-model="queryParams.groupName"
            class="!w-240px"
            clearable
            placeholder="请输入文件组名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <ns-input
            v-model="queryParams.fileName"
            class="!w-240px"
            clearable
            placeholder="请输入文件名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        ref="treeTableRef"
        :data="list"
        row-key="id"
        :default-expand-all="isExpandAll"
        max-height="480"
      >
        <el-table-column type="selection" width="85" />
        <el-table-column :show-overflow-tooltip="true" prop="name" label="文件名称">
          <template #default="scope">
            <el-icon v-if="scope.row.type === 1"><Folder /></el-icon
            ><span style="margin-left: 5px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <!-- <el-button type="primary" :disabled="formLoading" @click="submitForm">{{
        step === 1 ? '下 一 步' : '确 认'
      }}</el-button>
      <el-button v-if="step === 2" type="primary" @click="step = 1">上 一 步</el-button> -->

      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 认</el-button>

      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { Folder } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import { getFileTree } from '@/api/develop/file'
import { createClusterTask } from '@/api/develop/clusterTask'
const dialogVisible = ref(false) // 弹窗的是否展示
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const step = ref<1 | 2>(1)
const isExpandAll = ref(false) // 是否展开，默认全部折叠
const dialogState = computed(() => {
  const state = {
    dialogWidth: 1000,
    dialogTitle: '新建任务'
  }
  if (step.value === 2) {
    state.dialogTitle = '选择文件'
    state.dialogWidth = 1000
  }
  return state
})

const Step1Ref = ref<FormInstance>()
const queryFormRef = ref<FormInstance>() // 搜索的表单
const treeTableRef = ref<InstanceType<typeof ElTable>>()

const formStep1Data = reactive({
  name: ''
})

const formStep1Rules = reactive({
  name: [{ required: true, message: '任务名称不能为空', trigger: ['blur', 'change'] }]
})

const loading = ref(false) // 列表的加载中
const formLoading = ref(false) // 表单的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  groupName: '',
  fileName: ''
})

/** 打开弹窗 */
const open = () => {
  getList()
  step.value = 1
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async (e) => {
  e.preventDefault()
  // 校验表单

  await Step1Ref.value?.validate()

  //提交
  // 获取选中的文件，并且过滤出文件（1为文件夹，2为文件）
  const filesId = treeTableRef.value
    ?.getSelectionRows()
    ?.filter((item) => item.type == 2)
    .map((file) => file.id)

  if (filesId && filesId.length <= 1) {
    message.warning('至少选择两个文件')
    return
  }
  formLoading.value = true
  try {
    await createClusterTask({
      name: formStep1Data.name,
      manageIds: filesId.join(',')
    })
    message.success(t('common.createSuccess'))
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFileTree(toRaw(queryParams))
    list.value = data
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false
  Step1Ref.value?.resetFields()
  queryFormRef.value?.resetFields()
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped>
.form-wrap-step1 {
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}
.c-file {
  font-size: 18px;
  font-weight: bold;
  color: #606266;
}
</style>
